package com.jdy.haoduoaiteacher.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.model.StudentInfoxxj;
import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.activity.BaseActivity;
import com.jdy.haoduoaiteacher.activity.LoginActivity;
import com.jdy.haoduoaiteacher.activity.MyLoveListActivity;
import com.jdy.haoduoaiteacher.activity.PersonalInformationActivity2;
import com.jdy.haoduoaiteacher.activity.PublishPhotoActivity;
import com.jdy.haoduoaiteacher.activity.SettingActivity;
import com.jdy.haoduoaiteacher.activity.WebViewContainerActivity;
import com.jdy.haoduoaiteacher.adapter.MyLoveStoryAdapter;
import com.jdy.haoduoaiteacher.enums.SelectionMode;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.ImUserSig;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeSysMessage;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.MemberType;
import com.jdy.haoduoaiteacher.model.StudentDeviceModel;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.socket.SocketThreadManager;
import com.jdy.haoduoaiteacher.util.ACache;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ImageUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.LePreference;
import com.jdy.haoduoaiteacher.util.PathUtil;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.RippleView;
import com.jdy.haoduoaiteacher.view.scrollview.OnScrollChangedCallback;
import com.jdy.haoduoaiteacher.widget.CustomCommonDialog;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.service.XGPushService;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static org.droidparts.Injector.getApplicationContext;

//import com.jdy.haoduoaiteacher.R;

//import com.jdy.haoduoaiteacher.activity.BabyPhotoCloudActivity;
//import com.jdy.haoduoaiteacher.util.ImHelper;
//import com.tencent.TIMConnListener;
//import com.tencent.TIMManager;
//import com.jdy.haoduoaiteacher.widget.CustomEditDialog;


/**
 * 个人中心
 *
 * @author hf
 */
public class TabMineFragment extends BaseFragment implements OnClickListener,
        OnScrollChangedCallback {

    private static final String TAG = TabMineFragment.class.getSimpleName();

    @InjectView(id = R.id.home_face_img, click = true)
    private RoundImageView mHomeFaceImageView;
    @InjectView(id = R.id.parentAccountIdTextView)
    private TextView username;
    @InjectView(id = R.id.home_top_background, click = true)
    private View home_top_background;
    //  @InjectView(id = R.id.rel_babycloudalbum, click = true)
//  private View rel_babycloudalbum;
    @InjectView(id = R.id.rel_publishpt, click = true)
    private View rel_publishpt;
    @InjectView(id = R.id.tv_desc)
    private TextView tv_desc;
    //  @InjectView(id = R.id.rel_scanbaby, click = true)
//  private View rel_scanbaby;
    @InjectView(id = R.id.rel_mybaby, click = true)
    private View rel_mybaby;
    @InjectView(id = R.id.expired_at_textview)
    private TextView expired_at_textview;
    @InjectView(id = R.id.scoreCenterLinearLayout, click = true)
    private View scoreCenterLinearLayout; // 积分商城
    @InjectView(id = R.id.tv_name, click = true)
    private TextView tv_name;
    @InjectView(id = R.id.tv_schoolname, click = true)
    private TextView tv_score;
    @InjectView(id = R.id.device_stateview, click = true)
    private TextView device_stateview;
    @InjectView(id = R.id.membershipPackageIntroLinearLayout, click = true)
    private View membershipPackageIntroLinearLayout;
    @InjectView(id = R.id.exitRippleView)
    private RippleView mExitRippleView;
    @InjectView(id = R.id.img_setting, click = true)
    private ImageView img_setting;
    @InjectView(id = R.id.tv_edit, click = true)
    private TextView tv_edit;
    @InjectView(id = R.id.img_arrow2)
    private ImageView img_arrow;
    @InjectView(id = R.id.listview_devices)
    private ListView listview_devices;
    @InjectView(id = R.id.bottomlyt)
    private LinearLayout bottomlyts;
    @InjectView(id = R.id.delete, click = true)
    private Button delete;
    @InjectView(id = R.id.select, click = true)
    private Button select;
    @InjectView(id = R.id.view_listh)
    private View view_listh;
//  @InjectView(id = R.id.tv_bindcode, click = true)
//  private TextView tv_bindcode;

    @InjectView(id = R.id.exit, click = true)
    private RelativeLayout exit;


    private LeUser mLeUser;
    private Bitmap mScaleCrop;

    private ImUserSig mUserSigWrapper;
    private BroadcastReceiver mReceiver = null;

    private List<LeSysMessage> mSysMessageList;
    @SuppressWarnings("unused")
    private BaseActivity mBaseActivity;

    @InjectView(id = R.id.profile_scrollview)
    private com.jdy.haoduoaiteacher.view.scrollview.ObservableScrollView mScrollView;

    @InjectView(id = R.id.profile_head_img)
    private ImageView mHeadImg;

    @InjectView(id = R.id.tv_classname)
    private TextView tv_classname;

    private String account;

    private String userclass;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
        }
    };

    @SuppressLint("ValidFragment")
    public TabMineFragment(BaseActivity ba) {
        mBaseActivity = ba;
    }

    public TabMineFragment() {
    }


    @Override
    public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
                             ViewGroup container) {
        View bodyView = LayoutInflater.from(mContext).inflate(
                R.layout.profile_layout_teacher, container, false);

        account = SPUtil.getString(getActivity(), "account", "");

        return bodyView;
    }

    public ArrayList<StudentDeviceModel> mStudentDeviceModelList;


    private void getBindDevices() {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity,
                                      ResponseResult result) {
                if (result.isSuccess()) {
                    if (Tools.isNotNullStr(result.data)) {
//                try {
//                  JSONArray array = new JSONArray(result.data);

                        Log.i("test", result.data);

//                  mStudentDeviceModelList = (ArrayList<StudentDeviceModel>) JsonSerializer
//                          .getInstance().deserialize(array.toString(),
//                                  ArrayList.class, StudentDeviceModel.class);
//                  mStudentDeviceModelList = (ArrayList<StudentDeviceModel>) JsonSerializer
//                          .getInstance().deserialize(array.toString(),
//                                  ArrayList.class, StudentInfoxxj.class);

                        StudentInfoxxj info = GsonUtil.jsonToBean(result.data, StudentInfoxxj.class);

//                  if(!info.getStatus().equals("0")){

                        mStudentDeviceModelList = new ArrayList<>();

                        List<StudentInfoxxj.DataBean> list = info.getData();

                        for (int i = 0; i < list.size(); i++) {
                            StudentDeviceModel sdm = new StudentDeviceModel();
                            sdm.created_at = list.get(i).getCreated_at();
                            sdm.isChecked = false;
                            sdm.machine_id = list.get(i).getId();
                            sdm.nick_name = list.get(i).getApp_name();
                            sdm.machine.avatar = list.get(i).getApp_icon();
                            mStudentDeviceModelList.add(sdm);
                        }


//                  }


//                } catch (Exception e) {
//
//                }

                        if (mStudentDeviceModelList != null) {
                            mStoryAdapter = new MyLoveStoryAdapter(getActivity(), mStudentDeviceModelList);
                            listview_devices.setAdapter(mStoryAdapter);
                            Tools.setListViewHeightBasedOnChildren(listview_devices);
                            mStoryAdapter.notifyDataSetChanged();

                            if (!mStudentDeviceModelList.isEmpty()) {
                                if (mStudentDeviceModelList.size() < 6) {
                                    listview_devices.setVisibility(View.VISIBLE);
                                    view_listh.setVisibility(View.VISIBLE);
                                    img_arrow.setImageResource(R.drawable.downgray_arrow);
                                } else {
                                    listview_devices.setVisibility(View.GONE);
                                    view_listh.setVisibility(View.GONE);
                                    img_arrow.setImageResource(R.drawable.profile_to);
                                }
                            }
                        }
                    }
                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        Toast.makeText(getActivity(), result.data,
                                Toast.LENGTH_SHORT).show();
                    }
                }
                // }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

//        HashMap<String, Object> param_ = new HashMap<String, Object>();
//        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
//        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
//
//
//        Log.e("SNO222222",mLeUser.sno );
//        return HttpUtils.startRequest(HttpUtils.HOST_API
//                        + "/api/2.0/teacher/teacher_machine", param_,
//                HttpUtils.TAG_GET_REQUEST);

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("type", "1");
                param_.put("c", "15171454813");
                param_.put("role", "2");
                param_.put("userclass", "1");
                param_.put("platform", "2");


                return HttpUtils.startRequest(com.ycsj.goldmedalnewconcept.constant.Constant.SERVER_URL
                                + "YcsjApiMsg", param_,
                        HttpUtils.TAG_GET_REQUEST);


            }
        }).execute();
    }


    private void registerXG() {
        XGPushManager.registerPush(getApplicationContext(),
                new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object data, int flag) {
                        Log.e("TPush", "注册成功，设备token为：" + data.toString());
                        LeConfig.XG_TOKEN = data.toString();

                        if (LeConfig.isLogin) {
                            registerToken(LeConfig.XG_TOKEN);
                        }
                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Log.e("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
                    }
                });

        Intent service = new Intent(getActivity(), XGPushService.class);
        getActivity().startService(service);
    }

    private void registerToken(final String token) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {

            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                Log.e("TPush", "fksfjdsfdsf");
                if (result.isSuccess()) {
                    Log.d("TPush", "Response data is:" + result.data.toString());
                }
            }

            @SuppressWarnings("unused")
            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();

                int age = 0;
                String apellationName = null, nickname = null, headImage = null;

                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                if (age != 0) {
                    param_.put(HttpUtils.TAG_AGE_I, String.valueOf(age));
                }
                if (apellationName != null) {
                    param_.put(HttpUtils.TAG_APPELLATION_NAME_I, apellationName);
                }
                if (nickname != null) {
                    param_.put(HttpUtils.TAG_NICK_NAME_I, nickname);
                }
                if (headImage != null) {
                    param_.put(HttpUtils.TAG_HEAD_IMAGE_I, headImage);
                }
                param_.put(HttpUtils.TAG_PLATFORM_I, "android");
                if (Tools.isNotEmpty(token)) {
                    param_.put(HttpUtils.TAG_TOKEN_I, token);
                }

                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.UPDATE_PARENT_METHOD_PUT + mLeUser.sno, param_,
                        HttpUtils.TAG_PUT_REQUEST);

            }
        }).execute();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();

        registerXG();

        listview_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                Intent intent = new Intent(getActivity(),
                        MyLoveListActivity.class);
                intent.putExtra("studentmodel", mStudentDeviceModelList.get(position));
                startActivity(intent);

            }
        });

        mStudentDeviceModelList = new ArrayList<>();
        mLeUser = MyTeacherApp.getInstance().getUserTeacher();
        if (mLeUser == null) {
            mLeUser = Tools.restoreLeUser();
            if (mLeUser == null) {
                Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        }

        getViews();

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if ("updateparentheadimage".equals(action)) {
                    SharedPreferences prefs = mContext.getSharedPreferences(
                            Constant.USER_INFO, Context.MODE_PRIVATE);

                    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
                    if (Tools.isNotEmpty(parentImagePath)) {
                        Uri parentUri = Uri.parse(parentImagePath);

                        Bitmap originalBitmap = ImageUtils.getBitmapFromUri(mContext,
                                parentUri);
                        if (originalBitmap != null) {
                            mScaleCrop = ImageUtils.scaleCropToFit(originalBitmap, 300, 300,
                                    true);
                        }

//            mHomeFaceImageView.setImageURI(null);
//            if (mScaleCrop != null)
//              mHomeFaceImageView.setImageBitmap(mScaleCrop);
                    } else if (Tools.isEmpty(parentImagePath) && mLeUser != null) {
                        for (MemberType item : mLeUser.member_types) {
                            if (item.type_id == 1) {
                                if (Tools.isNotEmpty(item.avatar)) {
                                    getHeadImage(item.avatar);
                                }
                                break;
                            }
                        }
                    } else if (Tools.isEmpty(parentImagePath) && mLeUser == null) {
                        //img_vip.setImageResource(R.drawable.diamond_gray);
                    }
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction("updateparentheadimage");
        mContext.registerReceiver(mReceiver, filter);
    }

    private String mbindCode;

    private void initView() {

        //设置头像
        String icon = SPUtil.getString(getActivity(), "icon", "");

        if (!TextUtils.isEmpty(icon)) {
            Picasso.with(getActivity()).load(icon).into(mHomeFaceImageView);
        }

        //设置昵称
        String nickname = SPUtil.getString(getActivity(), "name", "");
        username.setText(nickname);

        //设置学校
        String school = SPUtil.getString(getActivity(), "schoolName", "");
        tv_desc.setText(school);


        mLeUser = MyTeacherApp.getInstance().getUserTeacher();
        if (mLeUser != null) {
            if (mLeUser.member_types != null && !mLeUser.member_types.isEmpty()) {
                for (MemberType item : mLeUser.member_types) {
                    if (item.type_id == 1) {
                        if (Tools.isEmpty(item.nick_name)) {
//                          username.setText("好多爱教师");
                        } else {
//                          username.setText(item.nick_name);
                        }

                        if (Tools.isEmpty(item.desc)) {
//                          tv_desc.setText("武汉好多爱幼儿园");
                        } else {
                            if (Tools.isNotEmpty(item.desc2)) {
//                              tv_desc.setText(item.desc + "(" + item.desc2  + ")");
                            } else {
//                              tv_desc.setText(item.desc);
                            }
                        }


//                      tv_bindcode.setText("绑定密码 --- " + item.code);

                        mbindCode = item.code;
                        break;
                    }
                }
            }
        }
    }

    private void getViews() {
        img_setting.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mScrollView.setOnScrollChangedCallback(this);
        mExitRippleView
                .setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                                getActivity()).setMessage("确定要退出当前账号？")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
//                                        doExitApp();
                                    }
                                });

                        if (!getActivity().isFinishing()) {
                            cdb.create().show();
                        }
                    }
                });
    }

    private void setUserAvatar() {
        initView();

        SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);
        String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
        if (Tools.isNotEmpty(parentImagePath)) {
            Uri parentUri = Uri.parse(parentImagePath);

            if (mScaleCrop == null) {
                Bitmap originalBitmap = ImageUtils
                        .getBitmapFromUri(mContext, parentUri);
                if (originalBitmap != null) {
                    mScaleCrop = ImageUtils
                            .scaleCropToFit(originalBitmap, 300, 300, true);
                }
            }

//      mHomeFaceImageView.setImageURI(null);
//      if (mScaleCrop != null)
//        mHomeFaceImageView.setImageBitmap(mScaleCrop);
        } else if (Tools.isEmpty(parentImagePath) && mLeUser != null) {
            getHeadImage(mLeUser.member_types.get(0).avatar);
        } else if (Tools.isEmpty(parentImagePath) && mLeUser == null) {

        }
    }

    private void getHeadImage(String remoteHeadImageFilePath) {
        if (Tools.isNullStr(remoteHeadImageFilePath)) {
            return;
        }

        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    String path = PathUtil.getElderAvatarPath(mContext
                            .getApplicationContext());
                    FileOutputStream out = null;
                    File parentAvatarFile = new File(path);
                    try {
                        out = new FileOutputStream(parentAvatarFile);
                        result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                        // your
                        // Bitmap
                        // instance
                        // PNG is a lossless format, the compression factor (100) is
                        // ignored
                        SharedPreferences prefs = mContext.getSharedPreferences(
                                Constant.USER_INFO, Context.MODE_PRIVATE);
                        Uri parentAvatarUri = Uri.fromFile(parentAvatarFile);
                        prefs.edit()
                                .putString(Constant.PARENT_AVATAR, parentAvatarUri.toString())
                                .apply();
                        setUserAvatar();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (out != null) {
                                out.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (mLeUser != null && mLeUser.callname != null) {
                        if (mLeUser.callname.contains("爸爸")
                                || mLeUser.callname.contains("爷爷")
                                || mLeUser.callname.contains("外公")) {
//              mHomeFaceImageView
//                  .setImageResource(R.drawable.defaut_parent_avtar_male);
                        } else {
//              mHomeFaceImageView
//                  .setImageResource(R.drawable.defaut_parent_avtar_female);
                        }
                    }
                }
            }

            @Override
            protected Bitmap doInBackground(String... urls) {
                String urldisplay = urls[0];
                Bitmap resultImage = null;
                URL url;
                try {
                    url = new URL(urldisplay);
                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.connect();
                    InputStream in = urlConnection.getInputStream();
                    resultImage = BitmapFactory.decodeStream(in);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return resultImage;
            }
        }.execute(remoteHeadImageFilePath);

    }

//  private void jump2Login() {
//    Intent intent = new Intent();
//    intent.setClass(mContext, LoginActivity.class);
//    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
//        | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//    startActivity(intent);
//  }


    private MyLoveStoryAdapter mStoryAdapter;


    private void updateParentInfo(final String bindCode) {
        if (Tools.isNotEmpty(bindCode.trim())) {
            new CustomAsyncTask(getActivity(), new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity, ResponseResult result) {
                    if (result.isSuccess()) {
                        mbindCode = bindCode;
                        LeUser lu = JsonSerializer.getInstance().deserialize(result.data,
                                LeUser.class);
                        if (lu != null) {
                            MyTeacherApp.getInstance().setUser(lu);
                            Tools.saveLeUser(lu);
                        }
                        Intent it = new Intent();
                        it.setAction("updatepersonalinfo");
                        getActivity().sendBroadcast(it);

//            tv_bindcode.setText("绑定密码 --- " + bindCode);
                    } else {
                        if (Tools.isNotEmpty(result.data)) {
                            CommonUtil.showToask(getActivity(), result.data);
                        }
                    }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    param_.put("code", bindCode);

                    return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/update_profile"
                            , param_, HttpUtils.TAG_POST_REQUEST);
                }
            }).execute("请检查网络连接!");

        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.exit:       //退出小小金

                getActivity().finish();

                break;
            case R.id.rel_publishpt:
                intent.setClass(mContext, PublishPhotoActivity.class);
                startActivity(intent);
                break;
//      case R.id.rel_scanbaby:
//        final CustomEditDialogOne.Builder customBuilder = new CustomEditDialogOne.Builder(getActivity());
//        customBuilder.setTitle("设置绑定密码").setEditText(mbindCode)
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                  @Override
//                  public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                  }
//                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//          @Override
//          public void onClick(DialogInterface dialog, int which) {
//           String bindCode = customBuilder.getEditText();
//            if (Tools.isNotEmpty(bindCode)) {
//              if (bindCode.length() != 6) {
//                CommonUtil.showToask(getActivity(), "密码长度必须为6位!");
//              } else {
//                dialog.dismiss();
//                updateParentInfo(bindCode);
//              }
//            } else {
//              CommonUtil.showToask(getActivity(), "绑定密码不能为空!");
//            }
//          }
//        });
//
////        customBuilder.getInputEditText().setText(mbindCode);
//
//        if (!getActivity().isFinishing()) {
//          customBuilder.create().show();
//        }
//
//        break;
            case R.id.rel_mybaby:
                if (listview_devices.getVisibility() == View.VISIBLE) {
                    listview_devices.setVisibility(View.GONE);
                    view_listh.setVisibility(View.GONE);
                    img_arrow.setImageResource(R.drawable.profile_to);
                } else {
                    listview_devices.setVisibility(View.VISIBLE);
                    view_listh.setVisibility(View.VISIBLE);
                    img_arrow.setImageResource(R.drawable.downgray_arrow);
                }
                break;
            case R.id.tv_edit:
                if (!bottomlyts.isShown()) {
                    bottomlyts.setVisibility(View.VISIBLE);
                    tv_edit.setText("取消");

                    mStoryAdapter.setEditor(true);
                    mStoryAdapter.notifyDataSetChanged();
                } else {
                    bottomlyts.setVisibility(View.GONE);

                    if (mStoryAdapter != null) {
                        mStoryAdapter.setEditor(false);
                        mStoryAdapter.notifyDataSetChanged();

                        if (mStudentDeviceModelList != null) {
                            for (StudentDeviceModel item : mStudentDeviceModelList) {
                                item.isChecked = false;
                            }
                        }
                    }
                    tv_edit.setText("编辑");
                }
                break;
//    case R.id.rel_babycloudalbum:
//      intent.se
//
//
// tClass(mContext, BabyPhotoCloudActivity.class);
//      startActivity(intent);
//      CommonUtil.showToask(getActivity(), "敬请期待!");
//      break;
            case R.id.scoreCenterLinearLayout:
                intent.putExtra("h5url", "http://weixin.lexiaobao.net/xxbjf/");
                intent.setClass(mContext, WebViewContainerActivity.class);
                startActivity(intent);
                break;
            case R.id.img_setting:
                intent = new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
//    case R.id.Myvoice:
//      if (MyTeacherApp.getInstance().getUser() == null) {
//        jump2Login();
//      } else {
//        intent.setClass(mContext, MyVoiceActivity.class);
//        startActivity(intent);
//      }
//      break;
            case R.id.home_face_img:


            case R.id.home_top_background:
//      if (MyTeacherApp.getInstance().getUser() == null) {
//        jump2Login();
//      } else {
                intent.setClass(mContext, PersonalInformationActivity2.class);
                startActivity(intent);
//      }
                break;
//    case R.id.Mylove:
//      if (MyTeacherApp.getInstance().getUser() == null) {
//        jump2Login();
//      } else {
//        intent.setClass(mContext, MyLoveListActivity.class);
//        startActivity(intent);
//      }
//
//      break;
            case R.id.membershipPackageIntroLinearLayout:
                if (MyTeacherApp.getInstance().getUser() == null) {
//        jump2Login();
                } else {
//        intent.setClass(mContext, MembershipCenterActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
//            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
                }
                break;
            case R.id.delete:

                deleteStory();
                break;
            case R.id.select:
                if (select.getText().toString().equals("全选")) {
                    if (mStoryAdapter != null) {
                        mStoryAdapter.setSelectMode(SelectionMode.SELECT_ALL);
                        mStoryAdapter.notifyDataSetChanged();
                    }

                    select.setText("取消全选");
                } else if (select.getText().toString().equals("取消全选")) {
                    if (mStoryAdapter != null) {
                        mStoryAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
                        mStoryAdapter.notifyDataSetChanged();
                    }

                    select.setText("全选");
                }
                break;

            default:
                break;
        }
    }

    private void deleteStory() {
        int selectCount = 0;
        if (mStudentDeviceModelList != null) {
            for (StudentDeviceModel item : mStudentDeviceModelList) {
                if (item != null && item.isChecked) {
                    ++selectCount;
                }
            }
        }

        if (selectCount > 0) {
            CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                    getActivity()).setMessage("确定删除吗？").setTitle("删除提示")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            if (mStudentDeviceModelList != null && !mStudentDeviceModelList.isEmpty()) {
                                final List<StudentDeviceModel> selectedRecordings = new ArrayList<StudentDeviceModel>();
                                String storyIds = "";

                                for (StudentDeviceModel item : mStudentDeviceModelList) {
                                    if (item.isChecked) {
                                        selectedRecordings.add(item);
                                        storyIds += item.id;
                                        storyIds += ",";
                                    }
                                }

                                if (Tools.isNotEmpty(storyIds)) {
                                    storyIds = storyIds.substring(0, storyIds.length() - 1);
                                }

                                if (selectedRecordings.size() > 0) {
                                    //showloading("");
                                    final String finalStoryIds = storyIds;
                                    new CustomAsyncTask(getActivity(),
                                            new IAsyncTask() {
                                                @Override
                                                public void onRecieveData(Activity activity,
                                                                          ResponseResult result) {

                                                    //  dismissLoading();
                                                    // if (result != null && result.isSuccess()) {
                                                    for (StudentDeviceModel rItem : selectedRecordings) {
                                                        mStoryAdapter.remove(rItem);
                                                    }
                                                    mStoryAdapter.removeSelection();

                                                    if (Tools.isNotNullStr(result.data)) {
                                                        Toast.makeText(getActivity(),
                                                                result.data, Toast.LENGTH_SHORT).show();
                                                    }
                                                    // }
                                                }

                                                @Override
                                                public ResponseResult doInbackground(Activity activity) {
                                                    if (mLeUser == null) {
                                                        mLeUser = Tools.restoreLeUser();
                                                    }

                                                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                                                    param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                                                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                                                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                                                    + "/api/2.0/teacher/teacher_machine/" + finalStoryIds,
                                                            param_, HttpUtils.TAG_DELETE_REQUEST);
                                                }
                                            }).execute();

                                }
                                dialog.dismiss();
                            }
                        }
                    });
            cdb.create().show();
        } else {
            Toast.makeText(getActivity(),
                    "未选中任何条目!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            // loadFocusers();
            //  loadMessageData();
            setUserAvatar();

//      getBindDevices();

            //请求数据
            http();

            LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
            if (lu != null && username != null) {
                if (lu.member_types != null && !lu.member_types.isEmpty()) {
                    for (MemberType item : lu.member_types) {
                        if (item.type_id == 1) {
                            if (Tools.isEmpty(item.nick_name)) {
//                username.setText("好多爱教师");
                            } else {
//                username.setText(item.nick_name);
                            }

                            if (Tools.isEmpty(item.desc)) {
//                tv_desc.setText("武汉好多爱幼儿园");
                            } else {
                                if (Tools.isNotEmpty(item.desc2)) {
//                      tv_desc.setText(item.desc + "(" + item.desc2  + ")");
                                } else {
//                      tv_desc.setText(item.desc);
                                }
                            }
                            break;
                        }
                    }
                }
            }

        } else {
            // TODO
        }
    }


    //请求服务器
    private void http() {


        final String classname = SPUtil.getString(getActivity(), "classnamexxj", "");
        userclass = SPUtil.getString(getActivity(), "classnumxxj", "1");

        Log.i("test", "userclass:" + userclass);
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "1");
        builder.add("c", account);
        builder.add("role", "2");
        builder.add("userclass", userclass);
        builder.add("platform", "2");
        Request request = new Request.Builder()
                .url(com.ycsj.goldmedalnewconcept.constant.Constant.SERVER_URL
                        + "YcsjApiMsg").post(builder.build())
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response arg0) throws IOException {

                StudentInfoxxj info = GsonUtil.jsonToBean(arg0.body().string(), StudentInfoxxj.class);

                if (info != null && !info.getStatus().equals("0")) {


                    mStudentDeviceModelList = new ArrayList<>();

                    List<StudentInfoxxj.DataBean> list = info.getData();

                    for (int i = 0; i < list.size(); i++) {
                        StudentDeviceModel sdm = new StudentDeviceModel();
                        sdm.created_at = list.get(i).getCreated_at();
                        sdm.isChecked = false;
                        sdm.machine_id = list.get(i).getId();
                        sdm.nick_name = list.get(i).getName();
                        sdm.machine = new LeMachine();
                        sdm.machine.avatar = list.get(i).getApp_icon();
                        mStudentDeviceModelList.add(sdm);
                    }
                } else {
                    mStudentDeviceModelList = new ArrayList<>();
                }

if(getActivity()!=null){

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        tv_classname.setText("我的班级--" + classname);

                        if (mStudentDeviceModelList != null) {
                            mStoryAdapter = new MyLoveStoryAdapter(getActivity(), mStudentDeviceModelList);
                            listview_devices.setAdapter(mStoryAdapter);
                            Tools.setListViewHeightBasedOnChildren(listview_devices);
                            mStoryAdapter.notifyDataSetChanged();

                            if (!mStudentDeviceModelList.isEmpty()) {
                                if (mStudentDeviceModelList.size() < 6) {
                                    listview_devices.setVisibility(View.VISIBLE);
                                    view_listh.setVisibility(View.VISIBLE);
                                    img_arrow.setImageResource(R.drawable.downgray_arrow);
                                } else {
                                    listview_devices.setVisibility(View.GONE);
                                    view_listh.setVisibility(View.GONE);
                                    img_arrow.setImageResource(R.drawable.profile_to);
                                }
                            }
                        }
                    }
                });
}
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart(TAG);

        handler.removeMessages(1);
        handler.sendEmptyMessageDelayed(1, 5000);

        String str = LePreference.getInstance().getString("clickmymsg");
        if (Tools.isNotEmpty(str)) {
            // tv_unread.setVisibility(View.GONE);
        }

        LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
        LeMachine lb = MyTeacherApp.getInstance().getBabyTeacher();

        if (lu != null && username != null && lb != null) {
            if (Tools.isNotNullStr(lb)) {
//        username.setText(lb.name + "的" + lu.callname);
            } else {
//        username.setText(lu.nickname);
            }
        } else if (lu != null && username != null) {
            if (lu.member_types != null && !lu.member_types.isEmpty()) {
                for (MemberType item : lu.member_types) {
                    if (item.type_id == 1) {
                        if (Tools.isEmpty(item.nick_name)) {
//              username.setText("好多爱教师");
                        } else {
//              username.setText(item.nick_name);
                        }

                        if (Tools.isEmpty(item.desc)) {
//              tv_desc.setText("武汉好多爱幼儿园");
                        } else {
                            if (Tools.isNotEmpty(item.desc2)) {
//                    tv_desc.setText(item.desc + "(" + item.desc2  + ")");
                            } else {
//                    tv_desc.setText(item.desc);
                            }
                        }

                        break;
                    }
                }
            }
        }
        setUserAvatar();

        // getBindDevices();
        http();
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }

        try {
            if (mContext != null && mReceiver != null) {
                mContext.unregisterReceiver(mReceiver);
                mReceiver = null;
            }
        } catch (Exception e) {
        }

        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);

        handler.removeMessages(1);
    }

    private void doExitApp() {
        // clear cache
        LePreference.getInstance().delete(LePreference.PREFERNCE_TELLSTORY_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSTORY_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSLIDE_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_SHARERANK_CACHE);
        LePreference.getInstance()
                .delete(LePreference.PREFERNCE_LAST_PUSHTIMESTAMP);
        LePreference.getInstance().delete(LePreference.PREFERNCE_NEXT_TIMESTAMP);
        LePreference.getInstance().delete("openradiodetailcount");
        LePreference.getInstance().delete("opensuitforbabydetailcount");

        LePreference.getInstance().delete("floatWindowVisibility");

        LePreference.getInstance().delete("playmode");

        Intent logoutIntent = new Intent("com.jdy.haoduoaiteacher.activity.logout");
        getActivity().sendBroadcast(logoutIntent);

        LeConfig.isLogin = false;

        SocketThreadManager.getInstance().stopThreads();
        SocketThreadManager.getInstance().releaseInstance();


        File dir = getActivity().getFilesDir();
        File file1 = new File(dir, Constant.TELL_STORY_SERACH_FILE);
        file1.delete();
        File file2 = new File(dir, Constant.PUSH_STORY_SERACH_FILE);
        file2.delete();

        ACache pCache = ACache.get(getActivity());
        pCache.clear();

        MyTeacherApp.getInstance().forgetUser();

        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.jdy.haoduoaiteacher.view.scrollview.OnScrollChangedCallback#onScroll(int,
     * int)
     */
    @Override
    public void onScroll(int l, int t, int oldl, int oldt) {
        // TODO Auto-generated method stub
        float newAlpha = (float) t / 500;

        int height = mScrollView.getHeight();
        int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
                .getMeasuredHeight();
        int dis = scrollViewMeasuredHeight - height;
        if (dis > 0) {
            newAlpha = (float) t / dis;
        }

//    if (newAlpha >= 0.8 && newAlpha <= 1.0) {
//      tv_name.setText("我的");
//    } else {
//      tv_name.setText("");
//    }

        // mHeadImg.setAlpha(1.0f * newAlpha);
    }
}
